local longbian = fk.CreateSkill{
  name = "lingling__longbian",
}

Fk:loadTranslationTable{
  ["lingling__longbian"] = "龙变",
  [":lingling__longbian"] = "回合结束时，你可以选择视为对一名本回合：对其造成过伤害/未对其造成过伤害的角色使用冰【杀】/【推心置腹】。",

  ["#lingling__longbian-invoke"] = "龙变：你可以视为对一名角色使用冰【杀】/【推心置腹】",
}

Fk:addTargetTip{
  name = "lingling__longbian",
  target_tip = function(self, player, to_select, selected, selected_cards, card, selectable, extra_data)
    if not selectable then return end
    if table.contains(extra_data.extra_data.targets1, to_select.id) then
      return "ice__slash"
    else
      return "sincere_treat"
    end
  end,
}

longbian:addEffect(fk.TurnEnd, {
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(longbian.name) then
      local room = player.room
      local targets1, targets2 = {}, {}
      room.logic:getActualDamageEvents(1, function (e)
        local damage = e.data
        if damage.from == player and damage.to ~= player then
          table.insert(targets1, damage.to)
        end
      end, Player.HistoryTurn)
      targets2 = table.filter(room:getOtherPlayers(player, false), function (p)
        return not table.contains(targets1, p) and player:canUseTo(Fk:cloneCard("sincere_treat"), p, { bypass_distances = true })
      end)
      targets1 = table.filter(targets1, function (p)
        return player:canUseTo(Fk:cloneCard("ice__slash"), p, { bypass_distances = true, bypass_times = true })
      end)
      if #targets1 > 0 or #targets2 > 0 then
        event:setCostData(self, { targets1 = targets1, targets2 = targets2 })
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets1, targets2 = event:getCostData(self).targets1, event:getCostData(self).targets2
    local to = room:askToChoosePlayers(player, {
      skill_name = longbian.name,
      min_num = 1,
      max_num = 1,
      targets = table.connect(targets1, targets2),
      prompt = "#lingling__longbian-invoke",
      cancelable = true,
      target_tip_name = longbian.name,
      extra_data = {
        targets1 = table.map(targets1, Util.IdMapper),
      },
    })
    if #to > 0 then
      to = to[1]
      event:setCostData(self, {tos = {to}, choice = table.contains(targets1, to) and "ice__slash" or "sincere_treat"})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).tos[1]
    local choice = event:getCostData(self).choice
    player:broadcastSkillInvoke(longbian.name)
    if choice == "ice__slash" then
      room:notifySkillInvoked(player, longbian.name, "offensive")
    else
      room:notifySkillInvoked(player, longbian.name, "control")
    end
    room:useVirtualCard(choice, nil, player, to, longbian.name, true)
  end,
})

return longbian
